package com.okwanshiwu.payment.wxUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

/**
 * post提交xml格式的参数
 */
public class HttpXmlUtils {

	/**
	 * 开始post提交参数到接口
	 * 并接受返回
	 * @param url
	 * @param xml
	 * @param method
	 * @param contentType
	 * @return
	 */
	public static String xmlHttpProxy(String url,String xml,String method,String contentType){
		InputStream is = null;
		OutputStreamWriter os = null;

		try {
			URL _url = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
			conn.setDoInput(true);   
			conn.setDoOutput(true);   
			conn.setRequestProperty("Content-type", "text/xml");
			conn.setRequestProperty("Pragma:", "no-cache");  
			conn.setRequestProperty("Cache-Control", "no-cache");  
			conn.setRequestMethod("POST");
			os = new OutputStreamWriter(conn.getOutputStream());
			os.write(new String(xml.getBytes(contentType)));
			os.flush();
			//返回值
			is = conn.getInputStream();
			return getContent(is, "utf-8");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(os!=null){os.close();}
				if(is!=null){is.close();}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 解析返回的值
	 * @param is
	 * @param charset
	 * @return
	 */
	public static String getContent(InputStream is, String charset) {
		String pageString = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		StringBuffer sb = null;
		try {
			isr = new InputStreamReader(is, charset);
			br = new BufferedReader(isr);
			sb = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			pageString = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null){
					is.close();
				}
				if(isr!=null){
					isr.close();
				}
				if(br!=null){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			sb = null;
		}
		return pageString;
	}

	public static String builderQueryOrderXml(QueryOrder qo){
		if(qo != null){
			StringBuffer bf = new StringBuffer();
			bf.append("<xml>");
			//start
			bf.append("<appid><![CDATA[");
			bf.append(qo.getAppid());
			bf.append("]]></appid>");
			
			bf.append("<mch_id><![CDATA[");
			bf.append(qo.getMch_id());
			bf.append("]]></mch_id>");
			
			bf.append("<nonce_str><![CDATA[");
			bf.append(qo.getNonce_str());
			bf.append("]]></nonce_str>");
			
			if(qo.getTransaction_id() != null && !"".equals(qo.getTransaction_id())){
				bf.append("<transaction_id><![CDATA[");
				bf.append(qo.getTransaction_id());
				bf.append("]]></transaction_id>");
			}else{
				bf.append("<out_trade_no><![CDATA[");
				bf.append(qo.getOut_trade_no());
				bf.append("]]></out_trade_no>");
			}
			
			bf.append("<sign><![CDATA[");
			bf.append(qo.getSign());
			bf.append("]]></sign>");
			//end
			bf.append("</xml>");
			return bf.toString();
		}
		return "";
	}
	/**
	 * post请求并得到返回结果
	 * @param requestUrl
	 * @param requestMethod
	 * @param output
	 * @return
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String output) {
		try{
			URL url = new URL(requestUrl);
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(requestMethod);
			if (null != output) {
				OutputStream outputStream = connection.getOutputStream();
				outputStream.write(output.getBytes("UTF-8"));
				outputStream.close();
			}
			// 从输入流读取返回内容
			InputStream inputStream = connection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			connection.disconnect();
			return buffer.toString();
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return "";
	}
	
	
	public static String refund(String mch_id, String data,String url) throws Exception{
//		KeyStore keyStore = KeyStore.getInstance("PKCS12");
//
//		InputStream instream = WeixinConfigUtils.class.getResourceAsStream("/apiclient_cert.p12");
//		try {
//			//指定PKCS12的密码(商户ID)
//			keyStore.load(instream, mch_id.toCharArray());
//		} finally {
//			instream.close();
//		}
//		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
//		    //指定TLS版本
//		    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
//		    sslcontext,new String[] { "TLSv1" },null,
//		    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//		    //设置httpclient的SSLSocketFactory
//		    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
//		    try {
//		        HttpPost httpost = new HttpPost(url); // 设置响应头信息
//		        httpost.addHeader("Connection", "keep-alive");
//		        httpost.addHeader("Accept", "*/*");
//		        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//		        httpost.addHeader("Host", "api.mch.weixin.qq.com");
//		        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
//		        httpost.addHeader("Cache-Control", "max-age=0");
//		        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
//		        httpost.setEntity(new StringEntity(data, "UTF-8"));
//		            CloseableHttpResponse response = httpclient.execute(httpost);
//		            try {
//		                HttpEntity entity = response.getEntity();
//		                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
//		                EntityUtils.consume(entity);
//		               return jsonStr;
//		            } finally {
//		                response.close();
//		            }
//		        } finally {
//		            httpclient.close();
//		        }
		return "";
	}
	


}
